using System;
using System.Drawing;
using Diagram;
using Diagram.Handles;
using Diagram.Utils;

namespace PetriDiagram.Shapes
{
    [Serializable]
    public class PlaceShapeAnchor : Anchor
    {
        private NetElementShape netElementShape;

        public PlaceShapeAnchor( NetElementShape parent )
            : base( parent )
        {
            netElementShape = parent;
        }


        public override void OnDrag( Movement movement )
        {
            Movement m = GetRealMovement();
            base.Location = m.Location;
            base.OnDrag( m );
        }

        public override void UpdatePosition()
        {
            base.Location = GetRealMovement().Location;
        }

        public override void OnDragDrop( Movement movement )
        {
            Movement m = GetRealMovement();
            base.Location = m.Location;
            base.OnDragDrop( movement );
        }

        private Movement GetRealMovement()
        {
            Handle h = GetSecondHandle();

            return new Movement( GeometricAlgorithms.SectionIntersectionWithCircle(
               netElementShape.Middle, netElementShape.Bounds.Width / 2, h.Location, netElementShape.Middle ),
            Size.Empty );
        }

        private Handle GetSecondHandle()
        {
            if( !IsStartingAnchor )
                return ParentConnection.Handles[ ParentConnection.Handles.Count - 2 ];
            else
                return ParentConnection.Handles[ 1 ];
        }
    }
}
